package edu.alanhome.portablelib;



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;  
import java.net.URLEncoder;
import java.util.ArrayList;
import org.jsoup.Jsoup;  
import org.jsoup.nodes.Document;  
import org.jsoup.nodes.Element;  
import org.jsoup.select.Elements; 

import android.util.Log;



public class dataFetcher {
	private int currentPage=0;
	private int pagesize=20;
	private String doctype="ALL";
	private String strsearchtype="title";
	private String searchstr;
	private String matchflag="forward";
	private String sort="CATA_DATE";
	private String dept="ALL";
	private String lang_code="ALL";
	private String showmode="list";
	private String orderby="DESC";
	private String onlylendable="no";
	private int count=20;
	
	private String initurl;
	private String GETurl;
	private Elements booklists;
	private Element  book;
	private String domain="http://opac.lib.dlut.edu.cn/opac/";
	private ArrayList<InforNode> books ;
	private Document doc;
	
	private String Ndoctype;
	private String Nbookname;
	private String Nbooknum;
	private String Nlink;
	private String Nbookstore;
	private String Nbooklendable;
	private String Nbookinfo;
	
	
	InforNode getItem(int idx)
	{
		Log.i("datafetcher-getItem","idx: "+idx);
		int sz = books.size();
		if(idx<sz)
			return books.get(idx);
		else
			return books.get(sz-1);
	}
	
	void genInitUrl()
	{
		initurl = domain;
		initurl += "openlink.php?";
		initurl += "dept="+this.dept;
		initurl += "&strText="+this.searchstr;
		initurl += "&strSearchType="+this.strsearchtype;
		initurl += "&doctype="+this.doctype;
		//initurl += "&lang_code="+this.lang_code;
		initurl += "&match_flag="+this.matchflag;
		initurl += "&displaypg="+this.pagesize;
		initurl += "&showmode"+ this.showmode;
		initurl += "&orderby="+this.orderby;
		initurl += "&sort="+this.sort;
		//initurl += "&onlylendable="+this.onlylendable;
		
	}
	void GenGETUrl()
	{
		if(currentPage==1)
		{
			this.genInitUrl();
			GETurl = initurl;         
		}
		else{
			GETurl = initurl+ "&count="+count+"&page="+currentPage;		
		}		 
	}
	int getNextPage() throws IOException
	{
		int bookssz = books.size();
		currentPage++;
		
		Log.i("datafetcher-getNextPage","currentpage: "+
				this.currentPage+" pagesize: "+
				this.pagesize+" count: "+
				this.count);
		if(this.currentPage*this.pagesize >= this.count + this.pagesize)
			return -1;
		
		GenGETUrl();
		System.out.println(GETurl);
		URL url = new URL(this.GETurl);  
        this.doc= Jsoup.parse(url, 20 * 1000);  //second arg is timeout
        if(this.currentPage==1)
        {
        	System.out.println(doc.select("strong.red").first().text());
        	count = Integer.valueOf( doc.select("strong.red").first().text()).intValue();  
        }
//    	}
        booklists = doc.select("div.list_books");
        for (Element element : booklists) {  
           
             this.Ndoctype = element.select("span.doc_type_class").text();
           
             this.Nbookname = element.select("a").text();
            
             
             this.Nlink = this.domain + element.select("a").attr("href");
            
             String all = element.select("h3").text();
             String pre = element.select("span.doc_type_class").text();
             pre += element.select("a").text();
            
             if(!all.equals(pre))
            	 all=all.substring(pre.length()+1);
             this.Nbooknum = all;
                                   
             String stores = element.select("p").text();
             int cnt=0;
             int len=stores.length();
             for(int i=0;i<len;++i)
             	if(stores.charAt(i)==' ')
             	{
             		cnt++;
             		if(cnt==2)
             		{
             			cnt=i;
             			break;
             		}
             	}            		
            
             String bookstore = stores.substring(0,cnt);
             String bookinfo  = stores.substring(cnt+1);
             this.Nbookstore = bookstore;
             this.Nbookinfo  = bookinfo;
             int pos = this.Nbookstore.lastIndexOf("可借复本");
             assert(pos!=-1);            	 
             this.Nbooklendable = this.Nbookstore.substring(pos);
             this.Nbookstore = this.Nbookstore.substring(0,pos-1);
            
            /* System.out.println(this.Ndoctype+" "+
             
            		 this.Nbookname+"|"+
    				 this.Nlink+"|"+
    				 this.Nbooknum+"|"+
    				 this.Nbookstore+"|"+
    				 this.Nbooklendable+"|"+
    				 this.Nbookinfo);
           
            */
             
             books.add(new InforNode(
    				 this.Ndoctype,
    				 this.Nbookname,
    				 this.Nlink,
    				 this.Nbooknum,
    				 this.Nbookstore,
    				 this.Nbooklendable,
    				 this.Nbookinfo));
 	    }
        
        return bookssz; //start from bookssz
	}
	void seturl(String url)
	{
		this.initurl = url;
	}
	void setOnlyLendable(String str)
	{
		this.onlylendable = str;
	}
	void setOderby(String odb)
	{
		this.orderby = odb;
	}
	void setShowMode(String sm)
	{
		this.showmode = sm;
	}
	void setLangCode(String str)
	{
		this.lang_code = str;
	}
	void setDetp(String str)
	{
		this.dept = str;
	}
	void setDocType(String typ)
	{
		this.doctype=typ;
	}
	void setStrsearchType(String typ)
	{
		this.strsearchtype = typ;
	}
	void setSearchstr(String str) throws UnsupportedEncodingException
	{
		//this.searchstr = str;
		this.searchstr = URLEncoder.encode(str,"utf8");
	}
	void setMatchFlag(String flag)
	{
		this.matchflag = flag;
	}
	void setSort(String st)
	{
		this.sort = st;
	}
		
	
	int getCurrentPage()
	{
		return this.currentPage;
	}
	
	int getPageSize()
	{
		return this.pagesize;
	}
	
	void setPageSize(int sz)
	{
		this.pagesize = sz;
	}
	int getcount()
	{
		return this.count;
	}
    void printbooks()
	{	
		int sz = books.size();
		for(int i=0;i<sz;++i)
		{
			InforNode tem = books.get(i);
			System.out.println(
					tem.doctype+"|"+
					tem.bookname+"|"+
					tem.link+"|"+
					tem.booknum+"|"+
					tem.bookinfo+"|"+
					tem.bookstore);
		}
	}
    void clear()
    {
    	books.clear();
    }
	dataFetcher()
	{
		books = new ArrayList<InforNode>();
	}
	/*public static void main(String [] args) throws IOException
	{
		dataFetcher df = new dataFetcher();
		df.setSearchstr("语言");
		df.getNextPage();
		df.getNextPage();
		df.printbooks();
	}*/
}
